package com.chb.catRecommend;

import java.io.IOException;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 *第一个mapreduce实现去重
 *这个非常简单， 将每行数据最为map的key
 *洗牌阶段（shuffle） 会进行分组， 默认key相同的分到一组， 有多个value
 *但是我们在reducer中输出key, 就保证了去重
 *
 */
public class Step1 {
	public static boolean run(Configuration conf, Map<String, String> paths) throws Exception {
		FileSystem fs = FileSystem.get(conf);
		Job job = Job.getInstance();
		job.setJar("C:\\Users\\12285\\Desktop\\cr.jar");
		job.setJarByClass(Step1.class);
		job.setJobName("Step1");
		
		job.setMapperClass(step1Mapper.class);
		job.setReducerClass(step1Reducer.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(NullWritable.class);
		
		Path in = new Path(paths.get("step1Input"));
		FileInputFormat.addInputPath(job, in);
		Path out = new Path(paths.get("step1Output"));
		if (fs.exists(out)) {
			fs.delete(out, true);
		}
		FileOutputFormat.setOutputPath(job, out);
		boolean f = job.waitForCompletion(true);
		return f;
	}
	static class step1Mapper extends Mapper<LongWritable, Text, Text, NullWritable> {
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			if (key.get() != 0) {
				context.write(value, NullWritable.get());
			}
		}
	}
	static class step1Reducer extends Reducer<Text, NullWritable, Text, NullWritable>{
		@Override
		protected void reduce(Text key, Iterable<NullWritable> values, Context context)
				throws IOException, InterruptedException {
			//直接输出key
			context.write(key, NullWritable.get());
		}
	}
}

